//
//  EditBatteryCommentView.swift
//  GreenDeal
//
//  Created by Moennig Q on 3/1/2023.
//

import UIKit
import SnapKit
import RxSwift
import RxRelay
import RxCocoa
class EditBatteryCommonView: View {
    private lazy var disposeBag = DisposeBag()
    var isBattery: BehaviorRelay<Bool> = BehaviorRelay(value: false)
    @objc dynamic var list = [InstallationDetailSystemDetailForBatteryModel]()
    var delList = [InstallationDetailSystemDetailForBatteryModel]()
    //
    let scrollView = DIYScrollView()
    let isBatteryBackView = UIView()
    let tableView = UITableView()
    var isBtterySwitchBtn: SwitchButton!
    //
    var scrollViewHeightConstraint: Constraint?
    var tableViewHeightConstraint: Constraint?
    override func setUpView() {
        self.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        //content
        scrollView.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
            self.scrollViewHeightConstraint = make.height.greaterThanOrEqualTo(0).constraint
        }
        //contentView
        let contentView = UIView()
        contentView.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        scrollView.addSubview(contentView)
        
        contentView.snp.makeConstraints { (make) in
            make.top.equalTo(scrollView)
            make.left.right.equalTo(self)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(scrollView)
        }
        //backView
        isBatteryBackView.drawBorder(backHexStr: "#F0F6F3FF", borderHexStr: "#005D2D66")
        contentView.addSubview(isBatteryBackView)
        isBatteryBackView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.greaterThanOrEqualTo(0)
        }
        //isBtterySwitchBtn
        isBtterySwitchBtn = SwitchButton()
        isBatteryBackView.addSubview(isBtterySwitchBtn)
        isBtterySwitchBtn.snp.makeConstraints { make in
            make.top.equalTo(Constant.TopBottomMargin)
            make.bottom.equalTo(-Constant.TopBottomMargin)
            make.right.equalTo(-Constant.LeftRightMargin)
            make.size.equalTo(SwitchButton.size)
        }
        //select battery
        let isBatteryTitle = ContentLabel()
        isBatteryTitle.text = R.string.localizable.doesYourSystemHaveABattery()
        isBatteryTitle.numberOfLines = 0
        isBatteryBackView.addSubview(isBatteryTitle)
        isBatteryTitle.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(Constant.LeftRightMargin)
            make.right.equalTo(isBtterySwitchBtn.snp.left).offset(-5)
            make.height.greaterThanOrEqualTo(0)
        }
        contentView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(isBatteryBackView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.right.equalTo(isBatteryBackView)
            self.tableViewHeightConstraint = make.height.greaterThanOrEqualTo(0).constraint
            make.bottom.equalToSuperview()
        }
        self.tableView.dataSource = self
        self.tableView.isScrollEnabled = false
        //处理滑动到最底部，reloadData时，界面抖动的问题
        self.tableView.estimatedRowHeight = 300
        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.isScrollEnabled = false
        self.tableView.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        self.tableView.separatorStyle = .none
        self.tableView.register(EditBatteryTableViewCell.self, forCellReuseIdentifier: EditBatteryTableViewCell.reuseCellIdentifier)
        if #available(iOS 15.0, *) {//iOS 15会默认有22点的高度,需要代码设置为0
            self.tableView.sectionHeaderTopPadding = 0
        }
        //
        isBtterySwitchBtn.rx.observe(Int.self, "tag").subscribe {[weak self] btnTag in
            guard let strongSelf = self else {return}
            strongSelf.endEditing(true)
            let onFlag: Bool = (btnTag.element == 1 ? true : false)
            strongSelf.isBattery.accept(onFlag)
            //开启有电池，且list有0条数据就默认增加一条 记录
            if strongSelf.isBattery.value && strongSelf.list.count == 0 {
                strongSelf.addOneBattery()
            }else{//没有电池
                for m: InstallationDetailSystemDetailForBatteryModel in strongSelf.list{
                    if m.id != 0  {//主键不为空，表示是来自数据库的数据
                        m.deleted_at = true
                        strongSelf.delList.append(m)
                    }
                }
                strongSelf.list.removeAll()
                strongSelf.tableView.reloadData()
            }
        }.disposed(by: self.disposeBag)
        //绑定is battery变化，控制数据是否显示
        self.isBattery.asObservable().subscribe(onNext: {[weak self] (onFlag) in
            guard let strongSelf = self else {return}
            strongSelf.tableView.isHidden = !onFlag
            if onFlag {
                strongSelf.tableView.reloadData()
            }else{
                strongSelf.tableViewHeightConstraint?.update(offset: 0)
            }
        }).disposed(by: disposeBag)
        //监听Contensize是获取Tableview 高度最准确的方法
        tableView.rx.observe(CGSize.self, "contentSize").subscribe { [weak self] tableViewSize in
            guard let strongSelf = self, let size = tableViewSize else {return}
            strongSelf.tableViewHeightConstraint?.update(offset: size.height)
        }.disposed(by: self.disposeBag)
    }
    //MARK: -增加一行battery信息
    func addOneBattery(){
        let newRow = InstallationDetailSystemDetailForBatteryModel()
        self.list.append(newRow)//insert(newRow, at: 0)
        self.tableView.reloadData()
    }
    func loadData(_ list: [InstallationDetailSystemDetailForBatteryModel], isBattery: Bool){
        self.isBattery.accept(isBattery)
        self.isBtterySwitchBtn.switchOn(self.isBattery.value)
        if self.isBattery.value {
            if list.count > 0{
                self.list = list
                self.tableView.reloadData()
            }else{
                self.addOneBattery()
            }
        }
    }
    
}
extension EditBatteryCommonView: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = EditBatteryTableViewCell(style: .default, reuseIdentifier: EditBatteryTableViewCell.reuseCellIdentifier)
        cell.selectModelClosure = {[weak self]  in
            guard let strongSelf = self else { return}
            strongSelf.showSelectModelView(indexPath.row){
                //通知数据校验:单元格中的编辑事件，dynamic list监听不到，list只能监听到新增删除
                strongSelf.rx.list.onNext(strongSelf.list)
            }
        }
        cell.changedSwitchClosure = {[weak self] (isOn) in
            guard let strongSelf = self else { return}
            strongSelf.list[indexPath.row].changed_the_default_battery_manufacturer_setting = isOn
        }
        cell.partOfAggreSwitchClosure = {[weak self] (isOn) in
            guard let strongSelf = self else { return}
            strongSelf.list[indexPath.row].battery_system_part_of_an_aggregated_control = isOn
        }
        cell.countTextfield.editingChangedClosure = {[weak self] (qty) in
            guard let strongSelf = self else { return}
            if let data = Int64(qty) {
                strongSelf.list[indexPath.row].number_batteries = data
            }else{
                strongSelf.list[indexPath.row].number_batteries = 0
            }
            cell.batteryRatingTextfield.text = strongSelf.list[indexPath.row].battery_rating
            //通知数据校验:单元格中的编辑事件，dynamic list监听不到，list只能监听到新增删除
            strongSelf.rx.list.onNext(strongSelf.list)
        }
        cell.deleteRowClosure = {[weak self]  in
            guard let strongSelf = self else { return}
            let batteryModel = strongSelf.list[indexPath.row]
            if batteryModel.battery_model != ""{
                Tool().showAlertViewWithTwoBtns(title: R.string.localizable.pleaseConfirm(),message: R.string.localizable.areYouSureToDelete(batteryModel.battery_model), cancelStr: R.string.localizable.cancel(), confirmStr: R.string.localizable.delete(),yesClosure: {
                    strongSelf.deleteBattery(indexPath.row)
                })
            }else{
                strongSelf.deleteBattery(indexPath.row)
            }
        }
        cell.setData(list, row: indexPath.row)
        return cell
    }
    //
    private func deleteBattery(_ row: Int){
        let batteryModel  = self.list[row]
        if batteryModel.id != 0  {//来自服务器的数据，加入删除list
            batteryModel.deleted_at = true
            self.delList.append(batteryModel)
        }
        self.list.remove(at: row)
        if self.list.count == 0{//
            self.isBattery.accept(false)
            self.isBtterySwitchBtn.switchOn(self.isBattery.value)
        }
        self.tableView.reloadData()
    }
    func showSelectModelView(_ row: Int,closure: @escaping (()->Void)){
        Tool().showSearchModelView(type: .battery,title: "Battery Model") {[weak self] result in
            guard let strongSelf = self else { return}
            if row < strongSelf.list.count{
                strongSelf.list[row].battery_storage_id = result.id
                strongSelf.list[row].battery_model = result.model_number
                strongSelf.list[row].battery_brand = result.name
                strongSelf.list[row].battery_series = result.series
                strongSelf.list[row].battery_capacity = result.battery_capacity
                strongSelf.tableView.reloadRows(at: [IndexPath(row: row, section: 0)], with: UITableView.RowAnimation.none)
                closure()
            }
        }
    }
}
